"use client"; // 让 Next.js 知道这是客户端组件

import React, { useState, useEffect } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import '@wangeditor/editor/dist/css/style.css' // 引入 css

export function MyEditor({ getContent, initContent = '' }) {
    // editor 实例
    const [editor, setEditor] = useState(null)                   // JS 语法

    // 编辑器内容
    const [html, setHtml] = useState('<p>hello</p>')



    const toolbarConfig = {}                        // JS 语法

    const editorConfig = {                         // JS 语法
        placeholder: '请输入内容...',
        MENU_CONF: {},
    }

    // 修改 uploadImage 菜单配置
    editorConfig.MENU_CONF['uploadImage'] = {
        server: '/api/upload',
        fieldName: 'file',
        base64LimitSize: 2 * 1024 * 1024, // 2MB 以内的图片转 Base64
        // 继续写其他配置...
        onSuccess: (file, res) => {
            // 图片上传并返回结果，result 即为图片 url
            debugger
            editor.cmd.do('insertHTML', `<img src="${result}" style="max-width:100%;"/>`)
        },
        

        //【注意】不需要修改的不用写，wangEditor 会去 merge 当前其他配置
    }

    // 及时销毁 editor ，重要！
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
        }
    }, [editor])

    useEffect(() => {
        setHtml(initContent)
    }, [initContent])



    return (
        <div className="item-center mt-5">
            <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
                <Toolbar
                    editor={editor}
                    defaultConfig={toolbarConfig}
                    mode="default"
                    style={{ borderBottom: '1px solid #ccc' }}
                />
                <Editor
                    defaultConfig={editorConfig}
                    value={html}
                    onCreated={setEditor}
                    onChange={(editor) => {
                        setHtml(editor.getHtml())
                        getContent(editor.getHtml())
                    }}
                    mode="default"
                    style={{ height: '300px', overflowY: 'hidden' }}
                />
            </div>
            {/* <div style={{ marginTop: '15px' }}>{html}</div> */}
        </div>
    )
}


// export default MyEditor;